/* PICKING.C */ 

/*
	Copyright (C) 2010 by Lesnikov Andrey <ozkriff@gmail.com>
	This file is part of ozkriff_game_2.

	ozkriff_game_2 is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	ozkriff_game_2 is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with ozkriff_game_2.  If not, see <http://www.gnu.org/licenses/>.

	See the COPYING file for more details.
*/

#include <stdbool.h>

#include "SDL/SDL.h"
#include "SDL/SDL_opengl.h"

#include "defines.h"
#include "camera.h"
#include "nograph.h"
#include "draw.h"
#include "gui.h"
#include "picking.h"

extern int PICKED_SMTH;
extern float HEX_IN, HEX_EX;
extern int cursorX, cursorY;
extern uint aX, aY;
extern int SELECTED_BUTTON;

#define PICK_BG  0 // code for backround
#define PICK_HEX 1 //code for terrain hex

void
draw_for_picking()
{
	glClearColor(0, 0, PICK_BG, 1);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	
	set_camera();
	
	glPushMatrix();
	glEnableClientState(GL_VERTEX_ARRAY);
	
	int x, y;
	for (y=0; y<MAP_SIZE_Y; y++) {
		for (x=0; x<MAP_SIZE_X; x++) {
			glColor3ub(x, y, PICK_HEX);
			draw_filled_hex();
			glTranslatef(2*HEX_IN, 0, 0);
		}
		if (y%2 == 0)
			glTranslatef(-HEX_IN, 1.5*HEX_EX, 0);
		else
			glTranslatef(+HEX_IN, 1.5*HEX_EX, 0);
		glTranslatef(-(2*HEX_IN *MAP_SIZE_X), 0, 0);
	}
	
	glDisableClientState(GL_VERTEX_ARRAY);
	glPopMatrix();
}



void
do_picking()
{
	glDisable(GL_CULL_FACE);

	draw_for_picking();
	draw_interface_for_picking();

	GLint viewport[4];
	GLubyte pixel[3];
	
	glGetIntegerv(GL_VIEWPORT, viewport);
	glReadPixels(cursorX, viewport[3]-cursorY, 1, 1, GL_RGB,
		     GL_UNSIGNED_BYTE, (void*)pixel);
	             
	//update active cell
	aX = pixel[0]; //TODO вот из-за этого и выбирается первая ячейка, вроде.
	aY = pixel[1];
	//printf("ax:%i, ay%i\n", aX, aY);
		
	PICKED_SMTH = (bool)pixel[2];
	//printf("%u\n", pixel[2]);
	if (pixel[2] > 1) { //если 3й элемент больше еденицы - мы тыркнулись в интерфейс
		//printf("some button\n");
		SELECTED_BUTTON = pixel[2]-2;
		//printf("%s\n", BUTTONS[ pixel[2]-2 ].name);
	} else {
		SELECTED_BUTTON = -1;
	}

	glEnable(GL_CULL_FACE);
}


